﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using PersonalHealth.Data.IService;
using PersonalHealth.Data.Service;
using System.ComponentModel;
using PersonalHealth.Data.Model;
using CardProduce.Card;

namespace Health_Solution.Views
{
    /// <summary>
    /// Login.xaml 的交互逻辑
    /// </summary>
    public partial class Login : Page
    {
        BackgroundWorker worker1;
        UInt32 kh = 0;
        string password = "FFFFFFFFFFFF";
        public Login()
        {
            InitializeComponent();
           
            this.Loaded += new RoutedEventHandler(Login_Loaded);
            this.Unloaded += new RoutedEventHandler(Login_Unloaded);
        }

        void Login_Unloaded(object sender, RoutedEventArgs e)
        {
            if (worker1 != null && worker1.IsBusy)
            {
                worker1.CancelAsync();
            }
        }


        void Login_Loaded(object sender, RoutedEventArgs e)
        {
            var mainWin = Window.GetWindow(this) as MainWindow;
            if (mainWin != null)
                mainWin.Title = "爱易通健康管理系统";

            try
            {
                CardSimpleAPI.ConnectByPassword(password, password);
            }
            catch (Exception ex)
            {
                return;
            }
            worker1 = new BackgroundWorker();
            worker1.WorkerSupportsCancellation = true;
            worker1.DoWork += (o1, e1) =>
            {
                while (true)
                {
                    while (CardSimpleAPI.RequestIDLE() != 0)
                    {
                        if (worker1.CancellationPending)
                        {
                            e1.Cancel = true;
                            return;
                        }
                        System.Threading.Thread.Sleep(500);
                    }
                    byte size = 0;
                    byte status = CardAPI.CascAnticoll(0, CardAPI.AntiCollision1, ref kh);
                    if (status != 0)
                        throw new CardException(CardAPI.GetErrorMsg(status));
                    status = CardAPI.CascSelect(CardAPI.AntiCollision1, kh, ref size);
                    if (status != 0)
                        throw new CardException(CardAPI.GetErrorMsg(status));
                    if (kh > 0)
                    {
                        break;
                    }
                }
            };
            worker1.RunWorkerCompleted += (o2, e2) =>
            {
                if (!e2.Cancelled)
                {
                    this.Dispatcher.Invoke(new Action(() =>
                    {
                        IUserService service = new UserService();
                        var user = service.LoginWithIcCard(kh.ToString());
                        if (user == null)
                        {
                            UI.Comm.Common.Tools.ShowMessage(false, "登陆错误！");
                            //MessageBox.Show("登陆错误！");
                            worker1.RunWorkerAsync();
                            return;
                        }
                        if (user is Doctor)
                        {
                            var currentWin = Window.GetWindow(this) as MainWindow;
                            Action onLogout = () => currentWin.ContentFrame.Content = new Login();
                            //var win = new HealthManagement.MainWindow(user as Doctor, onLogout);
                            //currentWin.Hide();
                            //win.Closed += new EventHandler(win_Closed);
                            //win.ShowDialog();

                            var window = new HealthManagement.MainWindow(user as Doctor, onLogout);
                            currentWin.Child = window;
                            currentWin.Title = "爱易通健康管理系统";
                            currentWin.ContentFrame.Content = window.Content;
                        }
                        if (user is MeasureUser)
                        {
                            var currentWin = Window.GetWindow(this) as MainWindow;
                            Action onLogout = () => currentWin.ContentFrame.Content = new Login();
                            var window = new PersonHealth.MainWindow(user as MeasureUser, onLogout);
                            currentWin.Child = window;
                            currentWin.Title = "";
                            currentWin.ContentFrame.Content = window.Content;
                        }

                    }), null);

                }
            };

            worker1.RunWorkerAsync();
        }
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            IMeasureUserService muSer = new MeasureUserService();
            var testUser = muSer.Find(c => c.UserTypeId == (int)UserType.TestUser).FirstOrDefault();
            if (testUser == null)
            {
                UI.Comm.Common.Tools.ShowMessage(false, "没有建立用户体验账号，请联系管理员！");
                //MessageBox.Show("没有建立用户体验账号，请联系管理员！");
                return;
            }

            var currentWin = Window.GetWindow(this) as MainWindow;
            Action onLogout = () => currentWin.ContentFrame.Content = new Login();
            var window = new PersonHealth.MainWindow(testUser as MeasureUser, onLogout);
            currentWin.Child = window;
            currentWin.Title = "";
            currentWin.ContentFrame.Content = window.Content;
        }

        void win_Closed(object sender, EventArgs e)
        {
            var currentWin = Window.GetWindow(this) as MainWindow;
            currentWin.Close();
        }

        private void Login_click(object sender, RoutedEventArgs e)
        {
            IUserService service = new UserService();
            var user = service.Login(tbName.Text, tbPsd.Password);
            if (user == null)
            {
                tbPsd.Clear();
                UI.Comm.Common.Tools.ShowMessage(false, "服务编号或者密码错误！");
                
                //MessageBox.Show("服务编号或者密码错误！");
                return;
            }
            if (user is Doctor)
            {
                var currentWin = Window.GetWindow(this) as MainWindow;
                Action onLogout = () => currentWin.ContentFrame.Content = new Login();
                //var win = new HealthManagement.MainWindow(user as Doctor, onLogout);
                //currentWin.Hide();
                //win.Closed += new EventHandler(win_Closed);
                //win.ShowDialog();

                var window = new HealthManagement.MainWindow(user as Doctor, onLogout);
                currentWin.Child = window;
                currentWin.Title = "爱易通健康管理系统";
                currentWin.ContentFrame.Content = window.Content;
            }
            if (user is MeasureUser)
            {
                var currentWin = Window.GetWindow(this) as MainWindow;
                Action onLogout = () => currentWin.ContentFrame.Content = new Login();
                var window = new PersonHealth.MainWindow(user as MeasureUser, onLogout);
                currentWin.Child = window;
                currentWin.Title = "";
                currentWin.ContentFrame.Content = window.Content;
            }
        }

        private void Image_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            shak.Visibility = shak.Visibility == Visibility.Collapsed ? Visibility.Visible : Visibility.Collapsed;
            dengl.Visibility = dengl.Visibility == Visibility.Collapsed ? Visibility.Visible : Visibility.Collapsed;

            if (dengl.Visibility == Visibility.Visible)
                tbName.Focus();
        }

        private void Grid_KeyUp(object sender, KeyEventArgs e)
        {
                if (dengl.Visibility == Visibility.Visible && e.Key == Key.Enter)
                    Login_click(sender, RoutedEventArgs.Empty as RoutedEventArgs);
            
        }
    }
}
